<template>
  <div>
    <div class="app-container">
      <h-table-list
        ref="tableRef"
        border
        type="local"
        :page-sizes="[10, 20]"
        :data="system_username.records"
        :columns="columns"
        :pagination-info="paginationInfo"
        :form-options="formOptions"
        @size-change="handleSizeChange"
      >
        <ListOpearteButton />
        <template slot="userType" slot-scope="scope">
          <p>
            <span v-if="scope.row.userType == '0'">PC端</span>
            <span v-if="scope.row.userType == '1'">手机端</span>
            <span
              v-if="scope.row.userType == '0,1' || scope.row.userType == '1,0'"
            >手机端,PC端</span>
          </p>
        </template>
        <!-- <template slot="createTime" slot-scope="scope">
          <p>
           {{scope.row.createdTime}}
          </p>
        </template> -->
        <template slot="enable" slot-scope="scope">
          <span v-if="scope.row.enable == 0">
            <div class="circle-14" />
            <span>停用</span>
          </span>
          <span v-if="scope.row.enable == 1">
            <div class="circle-13" />
            <span>启用</span>
          </span>
        </template>
        <template slot="operate-column" slot-scope="scope">
          <tableButton :row="scope.row" />
        </template>
      </h-table-list>
    </div>
    <DownloadIdentify
      :visible.sync="dialogFormVisible"
      title="账号管理"
      @cancel="cancel"
      @update="dialogSubmit"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="ruleForm.realName" maxlength="5" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="ruleForm.phone" maxlength="11" />
        </el-form-item>
        <el-form-item label="归属部门" prop="organId">
          <el-cascader
            v-model="ruleForm.organId"
            :options="app.allCode.department"
            :props="{ emitPath: false, checkStrictly: true }"
            clearable
          />
        </el-form-item>
        <el-form-item label="职位" prop="positionsId">
          <el-select v-model="ruleForm.positionsId">
            <el-option
              v-for="e in app.allDuty"
              :key="e.value || e"
              :label="e.label || e"
              :value="e.value || e"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="账号类别" prop="userType">
          <el-select v-model="ruleForm.userType" :multiple="true">
            <el-option label="PC" value="0" />
            <el-option label="APP" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="showPwd" label="登录账号" prop="userName">
          <el-col :span="12">
            <el-input v-model="ruleForm.userName" maxlength="20" />
          </el-col>
          <el-col :span="12">
            <span>6-20位，支持英文字母、阿拉伯数字，必须包含2种</span>
          </el-col>
        </el-form-item>
        <el-form-item v-if="showPwd" label="密码" prop="password">
          <el-col :span="12">
            <el-input v-model="ruleForm.password" maxlength="20" />
          </el-col>
          <el-col :span="12">
            <span>密码6-20位，包含字母、数字、符号中至少两种，字母区分大小写</span>
          </el-col>
        </el-form-item>
      </el-form>
    </DownloadIdentify>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import waves from '@/directive/waves' // waves directive
import DownloadIdentify from '@/components/FormDialog'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import ListOpearteButton from '@/components/AllButton/button2'
import tableButton from '@/components/AllButton/buttonForUserName'
import data from './const'
import { parseTime, listTotree } from '@/utils'
export default {
  name: 'SystemUsername',
  components: {
    DownloadIdentify,
    Pagination,
    tableButton,
    ListOpearteButton
  },
  directives: { waves },
  filters: {
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      dialogFormVisible: false,
      loadList: false,
      showPwd: false,
      ruleForm: {
        userName: '',
        userType: '',
        enable: null,
        password: '',
        realName: '',
        phone: '',
        organId: '',

        positionsId: ''
      },
      rules: {
        userName: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          {
            min: 6,
            max: 20,
            message: '请输入正确登录账号/账号已存在',
            trigger: 'blur'
          }
        ],
        realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        password: [
          {
            required: true,
            message: '请输入正确密码',
            trigger: 'blur'
          }
        ],
        organId: [
          { required: true, message: '请选择归属部门', trigger: 'blur' }
        ],
        positionsId: [
          { required: true, message: '请选择职位', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入正确手机号', trigger: 'blur' }
        ],
        userType: [
          { required: true, message: '请选择账号类别', trigger: 'blur' }
        ]
      },

      paginationInfo: {
        sizeChange: (e) => {
          console.log(e)
        },
        currentChange: (e) => {
          this.$store.dispatch('system_username/setListSearchParams', {
            current: e
          })
          this.getList(
            Object.assign(
              {},
              this.$store.state.system_username.listSearchParams
            )
          )
        },
        current: 1,
        total: 10
      },
      formOptions: {
        inline: true,
        submitBtnText: '查询',
        showResetBtn: true,
        searchParamsHandler: (params) => {
          console.log('查询')
          this.getList(params)
        },
        changevalue: (params) => {
          console.log(params, '++++params+++')
          this.$store.dispatch('system_username/setListSearchParams', params)
        },
        resetBtnCallback: () => {
          this.$store.dispatch('system_username/setListSearchParams', {})
          // this.getList(this.$store.state.system_username.listSearchParams);
          this.getList()
        },
        forms: [
          { prop: 'empno', label: '员工编号' },

          { prop: 'realName', label: '姓名' },
          { prop: 'phone', label: '手机号' },
          {
            prop: 'organId',
            label: '归属部门',
            itemType: 'cascader',
            options: [] // this.listTotree(this.$store.state.app.allCode.department),
          },

          {
            prop: 'positionsId',
            label: '职位',
            itemType: 'select',
            options: [
              { value: 0, label: '通用' },
              { value: 1, label: '专用' }
            ]
          },
          {
            prop: 'userType',
            label: '账号类别',
            itemType: 'select',
            options: [
              { value: '0', label: 'PC' },
              { value: '1', label: '手机' }
            ]
          }
        ]
      },
      columns: [
        { prop: 'empno', label: '员工编号' },

        {
          prop: 'realName',
          label: '姓名'
        },
        {
          prop: 'phone',
          label: '手机号'
        },

        { prop: 'organName', label: '归属部门' },
        { prop: 'positionsName', label: '职位' },
        { prop: 'userName', label: '登陆账号' },
        {
          prop: 'userType',
          label: '账号类别',

          slotName: 'userType'
        },
        {
          prop: 'createdTime',
          label: '创建时间',
          minWidth: 180
          //  slotName: "createdTime",
        },
        {
          prop: 'enable',
          label: '帐号状态',

          slotName: 'enable'
        },
        {
          prop: 'operate',
          label: '操作',
          minWidth: 300,
          slotName: 'operate-column',
          fixed: 'right'
        }
      ],
      tableData: []
    }
  },

  watch: {
    formChange: () => {}
  },
  computed: {
    ...mapState(['system_username', 'app'])
  },
  created() {
    // 初始获取几个基本数据,分别为操作状态,按钮权限等
    (this.formOptions.forms = this.formOptions.forms.map((e) => {
      const key = e.prop
      const data = this.$store.state.system_username.listSearchParams
      e.defaultValue = data[key] || ''
      return e
    })),
    // this.submitHandler=this.searchWithParams
    this.$store
      .dispatch(this.$store_url_button, {
        add: this.add,
        export: this.export,
        delete: this.delete,
        edit: this.edit,
        detail: this.detail,
        using: this.using,
        useless: this.useless,
        downloadTemplete: this.downloadTemplete,
        downloadIdentify: this.downloadIdentify,
        resetPwd: this.resetPwd
      })
      .then(async() => {
        const department = listTotree(
          this.$store.state.app.allCode.department
        )
        const allDuty = this.$store.state.app.allDuty
        this.$set(this.formOptions.forms[3], 'options', department)
        this.$set(this.formOptions.forms[4], 'options', allDuty)
        this.getList() // 表格数据
      })

    // this.listQuery=this.$store.state.basicEquipment.listSearchParams||{}  //操作状态
  },
  methods: {
    resetList() {
      // 重置搜索参数
      this.$refs.tableRef.$refs.searchForm.resetForm()
    },
    cancel() {
      this.dialogFormVisible = false
    },
    dialogSubmit() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          const params = JSON.parse(JSON.stringify(this.ruleForm))
          if (params && params.userType) {
            params.userType = params.userType.toString()
          }
          // 新增
          if (this.showPwd == true) {
            this.$store
              .dispatch('system_username/saveInfo', params)
              .then((res) => {
                this.resetList()
                this.dialogFormVisible = false
                this.$confirm(
                  `账号创建成功

若需要使用PC端功能，则还须为该账号分配权限

若仅需要使用移动端功能，则不须分配权限`,
                  '提示',
                  {
                    confirmButtonText: '去分配',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }
                ).then(() => {
                  this.$router.push('/system-manage/component/equipment/index')
                })
              })
              .catch((err) => {})
          } else {
            // 编辑
            this.$store
              .dispatch('system_username/updateInfo', params)
              .then((res) => {
                this.resetList()
                this.dialogFormVisible = false
              })
              .catch((err) => {})
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 自定义该业务模块下的按钮方法
    using(row) {
      this.$confirm(`确认启用该账号?`, '启用账号', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$store
            .dispatch('system_username/useUserInfo', row.id)
            .then((res) => {
              this.resetList()
              // this.dialogFormVisible=false
            })
            .catch((err) => {})
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消启用'
          })
        })
    },
    useless(row) {
      this.$confirm(
        `确认停用该账号?
      停用后该账号将不可使用`,
        '停用账号',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.$store
            .dispatch('system_username/uselessUserInfo', row.id)
            .then((res) => {
              this.resetList()
            })
            .catch((err) => {})
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消停用'
          })
        })
    },

    add(row) {
      this.ruleForm = {}
      this.showPwd = true
      this.dialogFormVisible = true
    },
    edit(row) {
      if (row.userType) {
        row.userType = row.userType.split(',')
      }
      console.log(row, '++++row++++')
      this.ruleForm = JSON.parse(JSON.stringify(row))
      this.showPwd = false
      this.dialogFormVisible = true
    },
    downloadIdentify(row) {
      console.log('下载设备标识卡')
      this.dialogFormVisible = true
    },
    async downloadTemplete(ids) {
      console.log('下载导出模板')
      const download = await this.$store.dispatch(
        'system_username/downloadTemplete'
      )
      // window.open(download.)
      console.log(download)
    },
    resetPwd(row) {
      console.log(row)
      this.$confirm(
        `确认重置密码？
临时密码将以短信形式发送至该账号绑定手机`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.$store
            .dispatch('system_username/resetPwd', row.id)
            .then((response) => {
              this.$message({
                type: 'success',
                message: '重置成功!'
              })
              this.resetList()
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '重置失败'
              })
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消重置'
          })
        })
    },
    delete(row) {
      console.log(row, '+++delete row++')
      this.$confirm(
        `该账号删除后不可恢复，确认删除？请先确保：
        1.该账号无审批任务
        2.该账号不在任一审批配置中`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.$store
            .dispatch('system_username/deleteDeviceInfo', row.id)
            .then((response) => {
              // this.$message({
              //   type: "success",
              //   message: "删除成功!",
              // });
              this.resetList()
            })
            .catch(() => {
              // this.$message({
              //   type: "info",
              //   message: "删除失败",
              // });
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    update() {},
    detail(row) {
      console.log(row)

      localStorage.setItem('/device-basic/component/detail/index', row.id)
      this.$router.push('/device-basic/component/detail/index')
    },
    import() {},
    export() {
      console.log('导出')
      this.$store.dispatch('system_username/exportFile')
    },
    // 弹窗的关闭
    cancel() {
      console.log('关闭弹窗')
      this.dialogFormVisible = false
    },
    // 更新弹窗数据
    updateDialog() {
      console.log('更新并关闭弹窗')
      this.dialogFormVisible = false
    },
    // 搜索按钮
    searchWithParams() {
      console.log('查询')
    },
    async getList(args) {
      // this.listLoading = true
      args = Object.assign({}, args, { adminFlag: 0 })
      await this.$store.dispatch('system_username/requestDeviceList', args)
      this.paginationInfo.total = this.$store.state.system_username.total
      this.paginationInfo.current = this.$store.state.system_username.current
    },
    handleFilter(args) {
      this.listQuery.page = 1
      this.getList(args)
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: '',
        timestamp: new Date(),
        title: '',
        status: 'published',
        type: ''
      }
    },
    handleCreate() {
      // this.resetTemp();
      // this.dialogStatus = "create";
      // this.dialogFormVisible = true;
      // this.$nextTick(() => {
      //   this.$refs["dataForm"].clearValidate();
      // });
      this.dialogFormVisible = true
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) =>
        filterVal.map((j) => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        })
      )
    }
  }
}
</script>
